package com.spx.core.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.omg.PortableInterceptor.SUCCESSFUL;

import com.spx.core.CoreActivator;
import com.spx.core.types.User;
import com.spx.core.ui.dialogs.LoginDialog;
import com.spx.kernel.ApplicationWorkbenchWindowAdvisor;
/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * 
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class LoginHandler extends AbstractHandler
{
	/**
	 * The constructor.
	 */
	public LoginHandler()
	{
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException
	{
		final Shell shell = HandlerUtil.getActiveWorkbenchWindow(event).getShell();
	    boolean successful =  false;
	
		LoginDialog loginDialog = new LoginDialog(shell);
		loginDialog.open();
		
		if (loginDialog.getReturnCode() == Dialog.OK){
			String password = loginDialog.getPassword();
			String userName = loginDialog.getUserName();
		    successful = CoreActivator.getDefault().getSecurityService().login(userName,password);
		   if (successful)
		   {
				ApplicationWorkbenchWindowAdvisor.getStatusSessionHolder().getStatusLine().setMessage("User:"+userName);

		   } else {
				final Status status = new Status(IStatus.ERROR, CoreActivator.PLUGIN_ID, 0, "Login Failed", null);
				ErrorDialog.openError(shell, "Error", "Could not login", status);
		   }
		    
		    
		    
		}
		
		
		return Boolean.valueOf(successful);
	}

	
}
